const Input = {};

let state ='';
cc.Class({
    extends: cc.Component,

    properties: {
    
    },


    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
        this.sp = cc.v2(0,0);
        this.state = '';
        this.speed = 300;
        this.heroAnima = this.node.getComponent(cc.Animation);
        console.log(' this.heroAnima', this.heroAnima);
        this.lv = this.node.getComponent(cc.RigidBody).linearVelocity;

    },

    update (dt) {

        if(Input[cc.macro.KEY.a]||Input[cc.macro.KEY.left]){
            // this.sp = cc.v2(-1,0);
            this.sp.x = -1;
            // this.state = 'hero_left';
            // this.node.x -= dt * speed;
        } else if(Input[cc.macro.KEY.d]||Input[cc.macro.KEY.right]){
            // this.node.x += dt * speed;
            // this.sp = cc.v2(1,0);
            this.sp.x = 1;
            // this.state = 'hero_right';
        }else{
            this.sp.x = 0;
        }

        if(Input[cc.macro.KEY.w]||Input[cc.macro.KEY.up]){
            // this.node.y += dt * speed;
            // this.sp = cc.v2(0,1);
            this.sp.y = 1;
            // this.state = 'hero_up';
        } else if(Input[cc.macro.KEY.s]||Input[cc.macro.KEY.down]){
            // this.node.y -= dt * speed;
            // this.sp = cc.v2(0,-1);
            this.sp.y = -1;
            // this.state = 'hero_down';  //一个函数块只干一个事情 是由 移动的方向决定动画的播放 位置的更新
        }else{
            this.sp.y = 0;
        }
        
        //将hero的移动方式改成物理的方式 设置线性速度
    

        if(this.sp.x){
            // this.node.x += this.sp.x * this.speed * dt;
            this.lv.x = this.sp.x * this.speed;
            this.lv.y = 0;
           
        } else if(this.sp.y){
            this.lv.y = this.sp.y * this.speed;
            this.lv.x = 0
            // this.node.y += this.sp.y * this.speed * dt;
        }else{
            this.lv = cc.v2(0,0);
        }
        this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;

        let state = '';
        if(this.sp.x === 1){
            state = 'hero_right';
        } else if(this.sp.x === -1){
            state = 'hero_left';
        }else if(this.sp.y === 1 ){
            state = 'hero_up';

        }else if(this.sp.y === -1){
            state = 'hero_down';
        }

        this.setState(state); //像状态这样的 最好只有一个函数去设置 或者播放动画

        // this.node.getComponent(Animation).play(this.state) error ts的写法
        // this.heroAnima.play(this.state);

    },

    onKeyDown(event){
        Input[event.keyCode] = 1;
    },

    onKeyUp(event){
        Input[event.keyCode] = 0;
    },

    setState(state){
        if( this.state !== state ){
            this.state = state;
            this.heroAnima.play(this.state);
        }

    },


});
